//
//  NSObject+Device.m
//  MIFI
//
//  Created by WangShuai WangShuai on 2019/6/4.
//  Copyright © 2019 NJMifi. All rights reserved.
//

#import "NSObject+Device.h"
#import <ifaddrs.h>
#import <net/if.h>
#import <NetworkExtension/NetworkExtension.h>
#import <SystemConfiguration/CaptiveNetwork.h>
@implementation NSObject (Device)
- (BOOL)isWIFIEnable {
    NSCountedSet *countedSet = [NSCountedSet new];
    struct ifaddrs *interfaces;
    if (!getifaddrs(&interfaces)) {
        for (struct ifaddrs *interface = interfaces; interface; interface = interface->ifa_next) {
            if ((interface->ifa_flags & IFF_UP) == IFF_UP) {
                NSString *ifa_name = [NSString stringWithUTF8String:interface->ifa_name];
                [countedSet addObject:ifa_name];
            }
        }
    }
    freeifaddrs(interfaces);
    // 网上有人判断的是awdl0
    BOOL open = [countedSet countForObject:@"en0"] > 1 ? YES : NO ||  [countedSet countForObject:@"awdl0"] > 1 ? YES : NO;
    return open;
}


- (void)connectWifiSSID:(NSString *)SSID andPassword:(NSString *)password withCallBack:(void(^)(NSError * error)) callback {
    
    if (@available(iOS 11.0, *)) {
        //Hachi_Office为wifi名称，hachismart是密码，这里换上你自己的wifi名和密码
         NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:SSID passphrase:password isWEP:NO];
        // 开始连接 (调用此方法后系统会自动弹窗确认)
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
            NSLog(@"%@", error);
            if (error) {
                //如果本来就链接了这个wifi,也会走到这里来
                NSLog(@"%@", error.localizedDescription);
                
                if (error.code == 8) {
                    return ;
                }
                
            }
            if (callback) {
                callback(error);
            }
            
            
        }];
}
    
}

@end
